package com.example.newland.application31;

import android.content.SharedPreferences;
import android.graphics.drawable.AnimatedImageDrawable;
import android.graphics.drawable.AnimationDrawable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView main_iv_bj_fans;
    private Button main_but_open;
    private Button main_but_close;
    private TextView main_tv_zhi;
    private ImageView mian_iv_fans;
    private ImageView main_iv_fans_switch;
    private ImageView main_iv_windo;
    private ImageView main_iv_windo_switch;
    private boolean main_fail = false;
    String token;
    private AnimationDrawable background;
    private AnimationDrawable fans;
    private AnimationDrawable window;

    int fansindex = 0;
    int windowindex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        main_iv_bj_fans = findViewById(R.id.main_iv_bj_fans);
        main_but_open = findViewById(R.id.main_but_open);
        main_but_close = findViewById(R.id.main_but_close);
        main_tv_zhi = findViewById(R.id.main_tv_zhi);
        mian_iv_fans = findViewById(R.id.mian_iv_fans);
        main_iv_fans_switch = findViewById(R.id.main_iv_fans_switch);
        main_iv_windo = findViewById(R.id.main_iv_windo);
        main_iv_windo_switch = findViewById(R.id.main_iv_windo_switch);

        main_but_open.setOnClickListener(this);
        main_but_close.setOnClickListener(this);
        main_iv_fans_switch.setOnClickListener(this);
        main_iv_windo_switch.setOnClickListener(this);

        //找到动画
        background = (AnimationDrawable) main_iv_bj_fans.getBackground();
        fans = (AnimationDrawable) mian_iv_fans.getBackground();

        window = (AnimationDrawable) main_iv_windo.getBackground();

        //登录---子线程请求网络
        new Thread(){
            @Override
            public void run() {
                super.run();
                String login_url = "http://api.nlecloud.com/Users/Login";
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("Account","17309339946");
                    jsonObject.put("Password","17309339946");
                    jsonObject.put("IsRememberMe",true);

                    String login_pamer = jsonObject.toString();

                    String login_json = HttpUrl.post(login_url, login_pamer, null);
                    Log.i("登录json",login_json);

                    //解析登录json
                    JSONObject jsonObject1 = new JSONObject(login_json);
                    int status = jsonObject1.getInt("Status");
                    if(status == 0){
                        JSONObject resultObj = jsonObject1.getJSONObject("ResultObj");
                        String accessToken = resultObj.getString("AccessToken");
                        Log.i("token",accessToken);

                        SharedPreferences config = getSharedPreferences("config", MODE_PRIVATE);
                        SharedPreferences.Editor edit = config.edit();
                        edit.putString(XindaluConfig.token,accessToken);
                        edit.commit();

                    }else{
                        Log.e("err","登录状态错误");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();


        //获取token
        new Thread(){
            @Override
            public void run() {
                super.run();
                //获取token
                SharedPreferences config = getSharedPreferences("config", MODE_PRIVATE);
                token = config.getString(XindaluConfig.token, "");
                while(true){
                    if(main_fail){
                        String co2_url = "http://api.nlecloud.com/devices/780686/Datas?deviceId=780686&ApiTags=I_co";
                        String co2_json = HttpUrl.get(co2_url, token);
                        Log.i("一氧化碳Json",co2_json);

                        //解析一氧化碳json
                        try {
                            JSONObject jsonObject = new JSONObject(co2_json);
                            int status = jsonObject.getInt("Status");
                            if(status == 0){
                                JSONObject resultObj = jsonObject.getJSONObject("ResultObj");
                                JSONArray dataPoints = resultObj.getJSONArray("DataPoints");
                                JSONObject jsonObject1 = dataPoints.getJSONObject(0);
                                JSONArray pointDTO = jsonObject1.getJSONArray("PointDTO");
                                JSONObject jsonObject2 = pointDTO.getJSONObject(0);
                                String co2_value = jsonObject2.getString("Value");

                                Log.i("一氧化碳的值", co2_value);

                                Message message = new Message();
                                message.what = 1;

                                Bundle bundle = new Bundle();
                                bundle.putString("co2_value",co2_value);
                                message.setData(bundle);

                                handler.sendMessage(message);
                                Float aFloat = Float.valueOf(co2_value);
                                if(aFloat > 300){
                                    //打开风扇
                                    String fans_url = "http://api.nlecloud.com/Cmds?deviceId=778003&apiTag=m_fans";
                                    HttpUrl.post(fans_url, "1", token);
                                }else{
                                    //关闭风扇
                                    String fans_url = "http://api.nlecloud.com/Cmds?deviceId=778003&apiTag=m_fans";
                                    HttpUrl.post(fans_url, "0", token);
                                }
                                if(aFloat > 800){
                                    //打开窗户
                                    String windowopen_url = "http://api.nlecloud.com/Cmds?deviceId=778003&apiTag=ddtg_k";
                                    HttpUrl.post(windowopen_url, "1", token);
                                    String windowclose_url = "http://api.nlecloud.com/Cmds?deviceId=778003&apiTag=ddtg_g";
                                    HttpUrl.post(windowclose_url, "0", token);
                                }else{
                                    //关闭窗户
                                    String windowopen_url = "http://api.nlecloud.com/Cmds?deviceId=778003&apiTag=ddtg_k";
                                    HttpUrl.post(windowopen_url, "0", token);
                                    String windowclose_url = "http://api.nlecloud.com/Cmds?deviceId=778003&apiTag=ddtg_g";
                                    HttpUrl.post(windowclose_url, "1", token);
                                }
                                windowindex = 1;
                                fansindex = 1;
                            }else{
                                Log.e("err", "一氧化碳状态错误");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.main_but_open:
                main_but_open.setEnabled(false);
                main_but_close.setEnabled(true);
                main_fail = true;
                break;
            case R.id.main_but_close:
                main_but_open.setEnabled(true);
                main_but_close.setEnabled(false);
                main_fail = false;
                break;
            case R.id.main_iv_fans_switch:
                new Thread(){
                    @Override
                    public void run() {
                        if(!main_fail){
                            fansindex++;
                            if(fansindex == 1){
                                //打开风扇
                                String fans_url = "http://api.nlecloud.com/Cmds?deviceId=778003&apiTag=m_fans";
                                HttpUrl.post(fans_url, "1", token);
                            }else if(fansindex == 2){
                                //关闭风扇
                                String fans_url = "http://api.nlecloud.com/Cmds?deviceId=778003&apiTag=m_fans";
                                HttpUrl.post(fans_url, "0", token);
                                fansindex = 0;
                            }

                            String s = String.valueOf(fansindex);

                            Message message = new Message();
                            message.what = 2;

                            Bundle bundle = new Bundle();
                            bundle.putString("fansindex", s);
                            message.setData(bundle);

                            handler.sendMessage(message);
                        }
                    }
                }.start();
                break;
            case R.id.main_iv_windo_switch:
                new Thread(){
                    @Override
                    public void run() {
                        if(!main_fail){
                            windowindex++;
                            if(windowindex == 1){
                                //打开窗户
                                String windowopen_url = "http://api.nlecloud.com/Cmds?deviceId=778003&apiTag=ddtg_k";
                                HttpUrl.post(windowopen_url, "1", token);
                                String windowclose_url = "http://api.nlecloud.com/Cmds?deviceId=778003&apiTag=ddtg_g";
                                HttpUrl.post(windowclose_url, "0", token);
                            }else if(windowindex == 2){
                                //关闭窗户
                                String windowopen_url = "http://api.nlecloud.com/Cmds?deviceId=778003&apiTag=ddtg_k";
                                HttpUrl.post(windowopen_url, "0", token);
                                String windowclose_url = "http://api.nlecloud.com/Cmds?deviceId=778003&apiTag=ddtg_g";
                                HttpUrl.post(windowclose_url, "1", token);
                                windowindex = 0;
                            }
                        }

                        String s = String.valueOf(windowindex);

                        Message message = new Message();
                        message.what = 3;
                        Bundle bundle = new Bundle();
                        bundle.putString("windowindex",s);
                        message.setData(bundle);
                        handler.sendMessage(message);
                    }
                }.start();
                break;
        }
    }

    Handler handler = new Handler(Looper.myLooper()){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case 1:
                    Bundle data = msg.getData();
                    String co2_value = data.getString("co2_value");
                    main_tv_zhi.setText(co2_value);
                    Float aFloat = Float.valueOf(co2_value);
                    if(aFloat > 300){
                        fans.start();
                        background.start();
                        main_iv_fans_switch.setImageResource(R.mipmap.switch_on);
                    }else{
                        fans.stop();
                        background.stop();
                        main_iv_fans_switch.setImageResource(R.mipmap.switch_off);
                    }
                    if(aFloat > 800){
                        window.start();
                        main_iv_windo_switch.setImageResource(R.mipmap.switch_on);
                    }else{
                        window.stop();
                        main_iv_windo_switch.setImageResource(R.mipmap.switch_off);
                    }
                    break;
                case 2:
                    Bundle data1 = msg.getData();
                    String fansindex = data1.getString("fansindex");
                    Integer integer = Integer.valueOf(fansindex);
                    if(integer == 1){
                        fans.start();
                        background.start();
                        main_iv_fans_switch.setImageResource(R.mipmap.switch_on);
                    }else{
                        fans.stop();
                        background.stop();
                        main_iv_fans_switch.setImageResource(R.mipmap.switch_off);
                    }
                    break;
                case 3:
                    Bundle data2 = msg.getData();
                    String windowindex = data2.getString("windowindex");
                    Integer integer1 = Integer.valueOf(windowindex);
                    if(integer1 == 1){
                        window.start();
                        main_iv_windo_switch.setImageResource(R.mipmap.switch_on);
                    }else{
                        window.stop();
                        main_iv_windo_switch.setImageResource(R.mipmap.switch_off);
                    }
                    break;
            }
        }
    };

}

//给线程取名字，打开监测按键按下，调用名字启动线程，关闭监测按键按下，调用名字关闭线程，为啥程序会停止运行
